package labs.laba_02;

import java.util.ArrayList;
import java.util.HashMap;

import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.DialogInterface.OnDismissListener;
import android.text.InputFilter;
import android.text.InputType;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.view.WindowManager.LayoutParams;
import android.view.ViewGroup;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

public class MainActivity extends Activity {
	public class MyCustomAdapter extends ArrayAdapter<HashMap<String, Object>> {
	    private final Context context;
	    private final ArrayList<TV> values;

	    public MyCustomAdapter(Context context, ArrayList<TV> values) {
	    	super(context, R.layout.list_item);
	        this.context = context;
	        this.values = values;
	    	if(!values.isEmpty()){
	    		HashMap<String, Object> m;
	    		byte i = 0;
		    	for(TV tv: values){
		    		m = new HashMap<String,Object>();
		    		m.put("checked", tv.getPower());
		    		m.put("text", "TV "+String.valueOf(i+1).toString()+"\t channel: "+String.valueOf(tv.getCurrentChannelIndex()).toString());
		    		//m.put("channel", String.valueOf(tv.getCurrentChannelIndex()).toString());
		    		this.add(m);
		    		i++;
		    	}
		    }
	    }

	    class ViewHolder{
	        public TextView textView;
	        public CheckBox checkBox;
	        public ViewHolder(CheckBox chb, TextView t){
	        	this.textView = t;
	        	this.checkBox = chb;
	        }
	    }

	    @Override
	    public View getView(int position, View convertView, ViewGroup parent) {
	    	final ViewHolder holder;
	    	if(convertView==null){
	    		LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	    		convertView = inflater.inflate(R.layout.list_item, parent, false);
	    		holder = new ViewHolder((CheckBox)convertView.findViewById(R.id.checkBox1), (TextView)convertView.findViewById(R.id.textView1));
	            convertView.setTag(holder);
	            convertView.setLongClickable(true);
	            convertView.setClickable(true);
	    	}else{
	    		holder = (ViewHolder)convertView.getTag();
	    	}
	    	Log.d(MainActivity.LOG_TAG, "getView executed " + position);
	    	holder.textView.setText((CharSequence)this.getItem(position).get("text"));
	    	holder.checkBox.setChecked((Boolean)this.getItem(position).get("checked"));
	    	holder.checkBox.setTag(position);
	    	holder.checkBox.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					CheckBox cch = (CheckBox)v;
					int pos = (Integer)cch.getTag();
					Log.d(MainActivity.LOG_TAG , "checked for position: "+pos);

					values.get(pos).setPower(cch.isChecked());
					Log.d(MainActivity.LOG_TAG, "Power changed:"+pos+" "+cch.isClickable());
//					Intent intent = new Intent(MainActivity.BROADCAST_ACTION);
//			        intent.putExtra("position", pos);
//			        intent.putExtra("checked", cch.isClickable());
//			        sendBroadcast(intent);
			        //Log.d(MainActivity.LOG_TAG, "broadcasted message:"+pos+" "+cch.isClickable());
				}
			});
	        return convertView;
	    }
	}

	public final static String LOG_TAG = "elisp";
	//public final static String BROADCAST_ACTION = "BR_change_TV_power";
	public final static byte DIALOG_CHANGE_CHANNEL = 1;

	private MyCustomAdapter madapter;
	private ListView mListView;

	private TVsManager tvsManager;
	private Dialog dialog;
//	private BroadcastReceiver br;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		tvsManager = new TVsManager();
		Log.d(LOG_TAG, "Create laba_02");
//		br = new BroadcastReceiver(){ // TODO for broadcast receiver, but it not used in process of developing
//			public void onReceive(Context context, Intent intent) {
//				byte position = (byte)intent.getIntExtra("position", -1);
//				boolean checked = intent.getBooleanExtra("checked", false);
//				Log.d(LOG_TAG, "onReceive: position = " + position + ", checked = " + checked);
//				if(0<=position) {
//					tvControl.getTV(position).setPower(checked);
//				}
//			}
//	    };
	}
	@Override
	protected void onPause() {
		super.onPause();
		//unregisterReceiver(br); // TODO for broadcast receiver, but it not used in process of developing
	}
	@Override
	protected void onResume() {
		super.onResume();
		setContentView(R.layout.activity_main);
		mListView = (ListView)findViewById(R.id.listView1);
		registerForContextMenu(mListView);
		refreshTVList();
		openMenu();
		//
		// TODO for broadcast receiver, but it not used in process of developing
//		IntentFilter intFilt = new IntentFilter(BROADCAST_ACTION);
//	    registerReceiver(br, intFilt);
	}
    @Override 
    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        if ((keyCode==KeyEvent.KEYCODE_BACK) && currentGroup!=null) {
//        	currentGroup = null;
//        	refreshViewList();
//            return true;
//        }
        return super.onKeyDown(keyCode, event);
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	menu.add(0,1,0,"add TV").setIcon(android.R.drawable.ic_menu_add);
    	menu.add(0,2,0,"exit").setIcon(android.R.drawable.ic_menu_close_clear_cancel);
        return super.onCreateOptionsMenu(menu);
    }
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
//    	if(currentGroup==null){
//    		menu.setGroupVisible(0, true);
//    		menu.setGroupVisible(1, false);
//    	}else{
//    		menu.setGroupVisible(0, false);
//    		menu.setGroupVisible(1, true);
//    	}
    	Log.d(LOG_TAG, "on Prepare to option menu");
    	return super.onPrepareOptionsMenu(menu);
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    	if(item.getTitle().equals("exit")){
    		finish();
    	}else if(item.getTitle().equals("add TV")){
    		tvsManager.addTV();
    		refreshTVList();
    		openMenu();
    	}
    	return super.onOptionsItemSelected(item);
    }
    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
    	if(v.getId()==R.id.listView1){
    		byte pos = (byte)((AdapterContextMenuInfo)menuInfo).position;
    		menu.setHeaderTitle("TV "+(pos+1)+" control");
    		menu.add(0, 1, 0, "Turn On");
    		menu.add(1, 2, 0, "Turn Off");
			menu.add(1, 3, 0, "Change channel");
			menu.add(2, 4, 0, "Delete TV");
			menu.setGroupVisible(2, true);
    		if(tvsManager.getTV(pos).getPower()){
    			menu.setGroupVisible(0, false);
    			menu.setGroupVisible(1, true);
    		}else{
    			menu.setGroupVisible(0, true);
    			menu.setGroupVisible(1, false);
    		}
    		tvsManager.setCurrentTVIndex(pos);
    		Log.d(LOG_TAG, "Creat context menu for list");
    	}
    	super.onCreateContextMenu(menu, v, menuInfo);
    }
    @Override
    public boolean onContextItemSelected(MenuItem item) {
    	if(item.getTitle()=="Turn On"){
    		tvsManager.getTV(tvsManager.getCurrentTVIndex()).setPower(true);
    	}else if(item.getTitle()=="Turn On"){
    		tvsManager.getTV(tvsManager.getCurrentTVIndex()).setPower(false);
    	}else if(item.getTitle()=="Change channel"){
    		showDialog(DIALOG_CHANGE_CHANNEL);
    	}else if(item.getTitle()=="Delete TV"){
    		tvsManager.delTV(tvsManager.getCurrentTVIndex());
    	}
    	refreshTVList();
    	return super.onContextItemSelected(item);
    }
    @Override
    protected Dialog onCreateDialog(final int id) {
    	Log.d(LOG_TAG, "Create dialog with id="+id);
    	if(DIALOG_CHANGE_CHANNEL==id){
    		//LinearLayout custView = (LinearLayout) getLayoutInflater().inflate(android.R.layout.simple_list_item_1, null);
    		LinearLayout customView = (LinearLayout) new LinearLayout(getApplicationContext());
    		final EditText tEdit = new EditText(getApplicationContext());
    		tEdit.setId(android.R.id.edit);
    		tEdit.requestFocus();
	        tEdit.setText("");
	        android.widget.TableRow.LayoutParams lp = new android.widget.TableRow.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
	        lp.setMargins(20, 0, 20, 0);
	        tEdit.setLayoutParams(lp);
	        tEdit.getLayoutParams().width = LayoutParams.FILL_PARENT;
	        tEdit.getLayoutParams().height = LayoutParams.WRAP_CONTENT;
	        tEdit.setGravity(Gravity.CENTER);
	        tEdit.setInputType(InputType.TYPE_CLASS_NUMBER);
	        tEdit.setSingleLine();
	        tEdit.setFilters(new InputFilter[]{new InputFilter.LengthFilter(2)});
	        customView.addView(tEdit);
	        AlertDialog.Builder adb = new AlertDialog.Builder(this);
	        adb.setView(customView);
	        adb.setTitle("enter new channel");
	        adb.setIcon(android.R.drawable.ic_menu_compass);
	        adb.setNegativeButton("Cancel", null);
	        adb.setPositiveButton("OK", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					String val = tEdit.getText().toString();
					if(val.trim().length()>0){
						byte valByte = Integer.valueOf(val).byteValue();
						if(tvsManager.getTV(tvsManager.getCurrentTVIndex()).setCurrentChannelIndex(valByte)){
							refreshTVList();
						}
					}else{
						//Toast.makeText(getApplicationContext(), "empty value", Toast.LENGTH_SHORT).show();
					}
					dialog.dismiss();
					tEdit.setText("");
				}
			});
	        dialog = adb.create();
	        dialog.getWindow().setSoftInputMode(LayoutParams.SOFT_INPUT_STATE_VISIBLE);
	        dialog.setOnCancelListener(new OnCancelListener() {
	        	public void onCancel(DialogInterface dialog) {
	        		Log.d(LOG_TAG, "Dialog id="+id+" Cancel");
	        	}
	        });
	        dialog.setOnDismissListener(new OnDismissListener() {
	        	public void onDismiss(DialogInterface dialog) {
	        		Log.d(LOG_TAG, "Dialog id="+id+"Dismiss");
	        	}
	        });
	        return dialog;
      }
      return super.onCreateDialog(id);
    }
    
    
    public void refreshTVList(){
    	setTitle("TV list");
    	madapter = new MyCustomAdapter(getApplicationContext(), tvsManager.getTVList());
		mListView.setAdapter(madapter);
    }
    private void openMenu(){
    	new Handler().postDelayed(new Runnable(){
			@Override
			public void run() {
				openOptionsMenu();
			}
		}, 100);
    }
//    private ArrayList<HashMap<String, Object>> convertToValue(ArrayList<TV> list){
//    	ArrayList<HashMap<String, Object>> adaptlsit = new ArrayList<HashMap<String, Object>>();
//    	if(!list.isEmpty()){
//    		HashMap<String, Object> m;
//    		byte i = 0;
//	    	for(TV tv: list){
//	    		m = new HashMap<String,Object>();
//	    		m.put("checked", tv.getPower());
//	    		m.put("text", "TV "+String.valueOf(i+1).toString()+"\t channel:"+String.valueOf(tv.getCurrentChannelIndex()).toString());
//	    		//m.put("channel", String.valueOf(tv.getCurrentChannelIndex()).toString());
//	    		adaptlsit.add(m);
//	    		i++;
//	    	}
//	    }
//    	return adaptlsit;
//    }
}
